import json,sys

lid="" #full id, e.g. "yangzhou"
name=""#names, e.g. "扬州"
id="" #short id, e.g. "yz"
desc="" #position prompts, e.g. "中央广场㊣大榕树"
trigs="" #actions e.g. "#action{大榕树(Rong Shu)} {set_position {yz}}"
routes="" # Route lists, e.g. #list Route_yz_haoz create {w;w;w;w;nw;w;n;n;nw;n;n};
conns="" # Connections, e.g. #var {{yangzhou} { {id}{yz} {name}{扬州} {desc}{扬州的中央广场大榕树}{conn}{bwc;bk;dp} } }

map_dict=json.load(open(sys.argv[1]))
#map_dict=json.load(open("/home/dawn/pkuxkx/data/map-pkuxkx.json"))

def wrap(a):
    b="{{{x}}}".format(x=str(a))
    return b

def actwarp(x,y):
    return "#action {{{a}}} {{xy.set_position {{{b}}}}};\n".format(a=x,b=y)

def reverse(x):
    route=x.split(";")
    r_route=""
    position_pair={"n":"s","s":"n","nu":"sd","sd":"nu","nd":"su","su":"nd","w":"e","e":"w","wu":"ed","ed":"wu","wd":"eu","eu":"wd","nw":"se","se":"nw","ne":"sw","sw":"ne","out":"enter","enter":"out"}
    while  len(route)!=0:
        step=route.pop()
        if step in position_pair.keys():
            r_route+=position_pair[step]+";"
        elif route[-1] not in position_pair.keys():
            r_route+=route.pop(-1)+";"
            r_route+=step+";"
        else:
            r_route+=step+";"
    return r_route[:-1]

tmp_cur_id2cur_lid={}
for cur_lid in map_dict.keys():
    cur_id=map_dict[cur_lid]["id"]
    tmp_cur_id2cur_lid[cur_id]=cur_lid

for cur_lid in map_dict.keys():
    try:
        lid = wrap(cur_lid)
        name = wrap(map_dict[cur_lid]["name"])
        id = wrap(map_dict[cur_lid]["id"])
        cur_id = map_dict[cur_lid]["id"]
        desc = wrap (map_dict[cur_lid]["desc"]) 
        trigs += actwarp(map_dict[cur_lid]["trig"],cur_lid)
    except KeyError:
        sys.stderr.write("在处理地点{long_id}时遇到异常\n".format(long_id=cur_lid))
        exit()
    conn=""
    for r in map_dict[cur_lid]["conn"]:
        cur_route=map_dict[cur_lid]["conn"][r]
        if cur_route=="#Reverse":
            cur_route=reverse(map_dict[tmp_cur_id2cur_lid[r]]["conn"][cur_id])
        routes += "#list Route_{frm}_{to} create {{{route}}};\n".format(frm=cur_id,to=r,route=cur_route)
        conn += r + ";"
    conn=wrap(conn[:-1])
    conns += lid+wrap("{id}"+id+"{name}"+name+"{desc}"+desc+"{conn}"+conn)




# Output the "compiled" tintin++ script
print("#class xy_data open;")
print("#var {xy.Area_list}",wrap("{0}{{name} {地点不存在} {desc} {如果你看到了这个就说明出错了}}"+conns),";\n")
print(routes)
print(trigs)
print("#class xy_data close")
